<?php

require_once("../config.inc.php");
require_once("../classes/class.payment.php");
require_once('../includes/mailer.class.php');
require_once('../classes/user.class.php');

$payment = new objPayment;
//$discount = new objDiscount;
//$discount->useDiscount($UserID);

$replyy = date("Y-m-d h:i:s")." -> "; //date for log file

// create vars for POST data
$invoice = $_POST['invoice'];
$amount = $_POST['LMI_PAYMENT_AMOUNT'];
$payment_no = $_POST['LMI_PAYMENT_NO'];
$reciever_wm = $_POST['LMI_PAYEE_PURSE'];
$payment_mode = $_POST['LMI_MODE']; //0-real; 1-test
$invoice_wm = $_POST['LMI_SYS_INVS_NO'];
$amount = $_POST['LMI_SYS_TRANS_NO'];
$payer_wm = $_POST['LMI_PAYER_PURSE'];
$payer_wmid = $_POST['LMI_PAYER_WM'];
$payment_date = $_POST['LMI_SYS_TRANS_DATE'];
//$amount = $_POST['LMI_SECRET_KEY'];



if ($invoice) {

	if (!$_GET['step']) $payment_status = "Completed";
	else if ($_GET['step']=="success") $payment_status = "Completed";
	else if ($_GET['step']=="fail") $payment_status = "Failed";

	$objSubscription = new objUserSubscription();
	$userInvoiceData = $objSubscription->getUserInvoiceData($invoice, $payment_status);
	//$discount->useDiscount($userInvoiceData['userID']);

	//check if DB record for this user exists
	$recordSet = $payment->db->Execute("SELECT u.Login FROM fa_subscriptions s LEFT JOIN fa_users u ON s.user_id=u.UserID WHERE s.user_id='".$objSubscription->userData['userID']."' and subscr_id='$invoice'");
	if ($recordSet) {
		while (!$recordSet->EOF) {
			$payer_email = $recordSet->fields['Login'];
			$recordSet->MoveNext();
		}
	}
	$cnter = $recordSet->RecordCount();


	switch ($payment_status)   {
		case $objSubscription->paymentCompleted:
			$objSubscription->activateSubscription = 1;
			$objSubscription->subscriptionStart = time();
   			$objSubscription->subscriptionEnd = true;

			//mail 2 us about new subscriber
			$mailshot = new objMailshot();
			$mailshot->subscrNotify($payer_email, $objSubscription->userData['userID'], $objSubscription->userData['subscrTime'], $objSubscription->userData['subscrPeriod'], "subscr_new", "WebMoney");

			//make discount inactive if user used it
   			//$discount->deactivateDiscount( $userInvoiceData['userID'] );
			break;
		default:
			break;
	}

	$objSubscription->processSubscription();




}

//////////////////////////////////////////////////////////////




//////////////////////////////////////////////////////////////
//// LOG ALL EVENTS ////
$replyy .= "IPN $invoice | $cnter |$payer_wm | $payer_wmid | $reciever_wm";
$fd = fopen("../logs/ipn_webmoney.log", "a");
fwrite($fd, $replyy."\r\n");
fclose($fd);


?>
